<?php

namespace App\Http\Controllers;

use App\Http\Model\Parking;
use App\Http\Model\Parkingspace;
use App\Http\Model\Rent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class ParkingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()//驶出列表页显示
    {
        $json_string = file_get_contents('./config/carcity.json');
        $carcity = json_decode($json_string, true);//导入车牌城市json数据

        $data = Parking::join('parkingspace','parking.parkingspace_no','parkingspace.id')//内连接查询  parking表 parkingspace表连表查询数据
            ->select('parking.*','parkingspace.is_rent')
            ->where('parking.state','=','0')
            ->orderBy('id','DESC')
            ->get()->toArray();
        return view('home/parking/index')->with('data',$data)->with('carcity',$carcity);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()//进入登记页面显示方法
    {
        $json_string = file_get_contents('./config/carcity.json');//导入车牌城市json数据
        $carcity = json_decode($json_string, true);
        return view('home/parking/create')->with('carcity',$carcity);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)//登记操作方法
    {

        if($request->isMethod('post')){//判断是否异步提交
            $input = Input::except('_token');
            $input['plate_num'] = strtoupper($input['plate_num']);//把车牌转大写
            $input['drivein_time'] = time();//获取当前登记时间
            $admin = session('admin');//获取session管理员
            $input['operator'] = $admin['name'];
            $parking_res = Parking::create($input)->toArray();//写入停车表 parking

            //判断是否是月租车
            $carcity = $input['carcity'];$plate_num = $input['plate_num'];$plate_type = $input['plate_type'];
            $rent_data = Rent::where('carcity','=',$carcity)
                ->where('plate_num','=',$plate_num)
                ->where('plate_type','=',$plate_type)
                ->first();
            $string = $rent_data ? '(月租车：'.$carcity.'·'.$plate_num.' 固定车位 NO.'.$rent_data['parkingspace_no'].')' : "";

            //写入车位表 parkingspace
            $plate_num = $input['carcity'].'·'.$input['plate_num'];
            if($rent_data){//判断是否月租车
                $parkingspace_res = DB::table('parkingspace')
                    ->where('id','=',$rent_data['parkingspace_no'])
                    ->update(['parking_id'=>$parking_res['id'],'status'=>'1']);
            }else{
                $parkingspace_no = $input['parkingspace_no'];
                $parkingspace_res = DB::table('parkingspace')
                    ->where('id','=',$parkingspace_no)
                    ->update(['plate_num'=>$plate_num,'parking_id'=>$parking_res['id'],'status'=>'1']);
            }

            if($parking_res&&$parkingspace_res){//根据结果返回数据
                return response()->json(['code'=>1,'msg'=>"登记成功 $string" ],200);
            }else{
                return response()->json(['code'=>0,'msg'=>'登记失败' ],200);
            }
        }else{
            return response()->json(['code'=>0,'msg'=>'请求方式不正确' ],200);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($pid)//驶出页面显示
    {
        $data = Parking::where('id','=',$pid)->first();//获取当前驶出车的信息
        $data = Parking::join('parkingspace','parking.parkingspace_no','parkingspace.id')//连表查询
            ->select('parking.*','parkingspace.is_rent')
            ->where('parking.id','=',$pid)
            ->first()->toArray();

        $time_diff = timeDiff($data['drivein_time'],time());//计算驶出与驶入的时间差值 秒
        $data['time_diff'] = $time_diff;

        $time_diff_sec = time() - $data['drivein_time'];
        $time_diff_min = $time_diff_sec / 3600;//时间差 秒转分

        $charge = 0;
        if($data['plate_type']==1){//小车
            if($time_diff_min<=1){//根据价格表计算收费款
                $charge = config('charge.CAR0_1');
            }elseif($time_diff_min>1&&$time_diff_min<=3){
                $charge = config('charge.CAR0_1') + config('charge.CAR2_3');
            }elseif($time_diff_min>3){
                $overtime = $time_diff_min - 3;
                $charge = config('charge.CAR0_1') + config('charge.CAR2_3') + ceil($overtime) * config('charge.CAR3');
            }
        }elseif($data['plate_type']==2){//大车
            if($time_diff_min<=1){
                $charge = config('charge.BUS0_1');
            }elseif($time_diff_min>1&&$time_diff_min<=3){
                $charge = config('charge.BUS0_1') + config('charge.BUS2_3');
            }elseif($time_diff_min>3){
                $overtime = $time_diff_min - 3;
                $charge = config('charge.BUS0_1') + config('charge.BUS2_3') + ceil($overtime) * config('charge.BUS3');
            }
        }
        if($data['is_rent']==1){//判断是否月租车
            $data['charge'] = 0;
        }else{
            $data['charge'] = $charge;
        }
        return view('home/parking/show')->with('data',$data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($pid)//修改停车信息页面显示
    {
        $json_string = file_get_contents('./config/carcity.json');
        $carcity = json_decode($json_string, true);//车牌城市数据导入
        $data = Parking::where('id','=',$pid)->first();//找车信息
        return view('home/parking/edit',compact('data','carcity'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)//修改parking信息
    {
        $input = Input::except('_method','_token');
        $res= DB::table('parking')->where('id','=',$id)->update($input);//修改停车表

        $plate_num = $input['carcity'].'·'.$input['plate_num'];
        DB::table('parkingspace')->where('parking_id','=',$id)->update(['plate_num'=>$plate_num]);//修改停车位表

        if($res){
            return response()->json(['code'=>1,'msg'=>'修改成功' ],200);
        }else{
            return response()->json(['code'=>0,'msg'=>'修改失败' ],200);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function handle(){
        $json_string = file_get_contents('./config/carcity.json');
        $carcity = json_decode($json_string, true);
        $data = Parking::orderBy('driveout_time','DESC')
            ->orderBy('drivein_time','DESC')
            ->orderBy('id','DESC')
            ->get();
        return view('home/parking/handle')->with('data',$data)->with('carcity',$carcity);
    }

    public function balance($id){
        $input = Input::all();
        $data = [
            'driveout_time' => time(),
            'time_diff' => $input['time_diff'],
            'charge' => $input['charge'],
            'state' => 1
        ];

        //修改车位表
        if($input['is_rent']){
            $pksdata = array('status'=>0,'parking_id'=>'0');
        }else{
            $pksdata = array(
                'status'=>0,
                'plate_num'=>'',
                'parking_id'=>'0'
            );
        }
        $parkingspace_res = DB::table('parkingspace')->where('parking_id','=',$id)->update($pksdata);
//        print_r($parkingspace_res);die;
        //修改停车表
        $parking_res= DB::table('parking')->where('id','=',$id)->update($data);
        if($parking_res&&$parkingspace_res){
            return response()->json(['code'=>1,'msg'=>'操作成功' ],200);
        }else{
            return response()->json(['code'=>0,'msg'=>'操作失败' ],200);
        }
    }

    public function search(){
        $input = Input::all();
        $carcity = $input['carcity'];
        $plate_num = $input['plate_num'];
        $data = [];
        if($carcity&&!$plate_num){
            $data = Parking::where('carcity','=',$carcity)->where('state','=','0')->get()->toArray();
        }elseif(!$carcity&&$plate_num){
            $data = Parking::where('plate_num','like',$plate_num.'%')->where('state','=','0')->get()->toArray();
        }elseif($carcity&&$plate_num){
            $data = Parking::where('carcity','=',$carcity)->where('plate_num','like',$plate_num.'%')->where('state','=','0')->get()->toArray();
        }
        if($data){
            return response()->json(['code'=>1,'msg'=>$data],200);
        }else{
            return response()->json(['code'=>0,'msg'=>'暂无数据'],200);
        }
    }

    public function handlesearch(){
        $input = Input::all();
        $carcity = $input['carcity'];
        $plate_num = $input['plate_num'];
        $data = [];
        if($carcity&&!$plate_num){
            $data = Parking::where('carcity','=',$carcity)->get()->toArray();
        }elseif(!$carcity&&$plate_num){
            $data = Parking::where('plate_num','like',$plate_num.'%')->get()->toArray();
        }elseif($carcity&&$plate_num){
            $data = Parking::where('carcity','=',$carcity)->where('plate_num','like',$plate_num.'%')->get()->toArray();
        }
        if($data){
            return response()->json(['code'=>1,'msg'=>$data],200);
        }else{
            return response()->json(['code'=>0,'msg'=>'暂无数据'],200);
        }
    }

    public function findrent(){
        $input = Input::all();
        $rent_res = DB::table('rent')
            ->where('carcity','=',$input['carcity'])
            ->where('plate_num','=',$input['plate_num'])
            ->first();
        if($rent_res){
            $rent_res = get_object_vars($rent_res);
            $content = $rent_res['carcity'].'·'.$rent_res['plate_num'].'为月租车<br>固定车位NO.'.$rent_res['parkingspace_no'].'<br>请直接登记！';
            return response()->json(['code'=>1,'msg'=>$content,'data'=>$rent_res],200);
        }else{
            return response()->json(['code'=>0,'msg'=>'暂无数据'],200);
        }
    }
}
